from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update
from app.models.user import User
from app.admin.schemas.user import UserCreate, UserUpdate
from app.security.utils import get_password_hash


async def get_user(db: AsyncSession, user_id: str, tenant_id: str) -> User:
    """
    根据用户ID获取用户
    """
    result = await db.execute(select(User).where(User.id == user_id and User.tenant_id == tenant_id))
    return result.scalar_one_or_none()


async def get_user_by_email(db: AsyncSession, email: str) -> User:
    """
    根据邮箱获取用户
    """
    result = await db.execute(select(User).where(User.email == email))
    return result.scalar_one_or_none()


async def get_user_by_login_name(db: AsyncSession, login_name: str) -> User:
    """
    根据登录名获取用户
    """
    result = await db.execute(select(User).where(User.login_name == login_name))
    return result.scalar_one_or_none()


async def get_users(db: AsyncSession, skip: int = 0, limit: int = 100, tenant_id: str = None):
    """
    获取用户列表，可按租户ID过滤
    """
    query = select(User)

    # 如果提供了租户ID，则按租户ID过滤
    if tenant_id:
        query = query.where(User.tenant_id == tenant_id)

    query = query.offset(skip).limit(limit)
    result = await db.execute(query)
    return result.scalars().all()


async def create_user(db: AsyncSession, user: UserCreate) -> User:
    """
    创建新用户
    """
    db_user = User(
        id=user.id,
        email=user.email,
        login_name=user.login_name,
        full_name=user.full_name,
        tenant_id=user.tenant_id,
        hashed_password=get_password_hash(user.password)
    )
    db.add(db_user)
    await db.commit()
    await db.refresh(db_user)
    return db_user


async def update_user(db: AsyncSession, user_id: str, user_update: UserUpdate) -> User:
    """
    更新用户信息
    """
    db_user = await get_user(db, user_id, tenant_id=user_update.tenant_id)
    if not db_user:
        return None

    update_data = user_update.dict(exclude_unset=True)
    if "password" in update_data and update_data["password"]:
        update_data["hashed_password"] = get_password_hash(update_data["password"])
        del update_data["password"]

    for key, value in update_data.items():
        setattr(db_user, key, value)

    await db.commit()
    await db.refresh(db_user)
    return db_user


async def delete_user(db: AsyncSession, user_id: str, tenant_id: str) -> bool:
    """
    删除用户
    """
    db_user = await get_user(db, user_id, tenant_id)
    if not db_user:
        return False

    await db.delete(db_user)
    await db.commit()
    return True


async def admin_reset_password(db: AsyncSession, user_id: str) -> bool:
    """
    管理员重置用户密码为默认密码
    """
    user = await get_user(db, user_id)
    if not user:
        return False

    # 重置为默认密码 "passwd123"
    default_password = "passwd123"
    hashed_password = get_password_hash(default_password)

    await db.execute(
        update(User)
        .where(User.id == user_id)
        .values(hashed_password=hashed_password)
    )
    await db.commit()
    return True


async def change_password(db: AsyncSession, user_id: str, old_password: str, new_password: str) -> bool:
    """
    用户修改密码（需要验证旧密码）
    """
    from app.security.utils import verify_password

    user = await get_user(db, user_id)
    if not user:
        return False

    # 验证旧密码
    if not verify_password(old_password, user.hashed_password):
        return False

    # 更新密码
    await db.execute(
        update(User)
        .where(User.id == user_id)
        .values(hashed_password=get_password_hash(new_password))
    )
    await db.commit()
    return True
